package is.ru.honn.rupin.data;

import is.ru.honn.rupin.domain.Pin;
import is.ruframework.data.RuData;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: gmatt
 * Date: 20.10.2012
 * Time: 13:04
 *
 * An SQL implementation of the PinDataGateway interface
 */
public class PinData extends RuData implements PinDataGateway {
    /**
     * Adds a pin to the database
     * @param pin passes the pin to be added to the database to the function
     */
    public void add(Pin pin) {
        SimpleJdbcInsert insertPin =
                new SimpleJdbcInsert(getDataSource())
                        .withTableName("ru_pins")
                        .usingGeneratedKeyColumns("id");
        Map<String, Object> parameters = new HashMap<String, Object>(6);
        JdbcTemplate queryResult = new JdbcTemplate(getDataSource());
        parameters.put("description", pin.getDescription());
        parameters.put("link", pin.getLink());
        parameters.put("image", pin.getImage());
        parameters.put("boardname", pin.getBoard().getName());
        parameters.put("username", pin.getCreator().getUsername());
        parameters.put("created", pin.getCreated());
        insertPin.execute(parameters);
    }

    /**
     * Fetches all pins by a specified user on a specified board
     * @param boardname passes the boardname to the function
     * @param username passes the username to the function
     * @return the list of pins
     */
    public List<Pin> getPinsByBoardnameAndCreator(String boardname, String username) {
        JdbcTemplate queryContent = new JdbcTemplate(getDataSource());
        List<Pin> pins = (List<Pin>)queryContent.query("SELECT * FROM ru_pins WHERE boardname=? AND username=?",
                new PinRowMapper(), new Object[]{boardname, username});
        return pins;
    }
}
